﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ChinaDynastyTours.Controls;
using ChinaDynastyTours.Models;
using DevExpress.XtraGrid.Columns;
using System.Threading;
using ChinaDynastyTours.Assets.DataSet;
using ChinaDynastyTours.Helpers;

namespace ChinaDynastyTours.Views
{
    public partial class IncomeForm : DevExpress.XtraEditors.XtraForm
    {
        private DataTable _dtIncomeItem;
        private DataTable _dtIncome;

        public IncomeForm()
        {
            InitializeComponent();
            
        }
        private void IncomeForm_Load(object sender, EventArgs e)
        {
            //初始化团下拉列表
            tourGroupInfoControl._InitTourGroupID = true;

            //初始化‘付款方’信息
            //CustomerEdit.Properties.DataSource = BaseInfoCtrl.GetCustomerData();

        }

        void Income_ColumnChanged(object sender, DataColumnChangeEventArgs e)
        {

            //string strIncomeItemId = e.Row["IncomeItemID"].ToString();
            ////string strReceivedPrice = RMBAmount.SummaryItem.SummaryValue.ToString();

            //decimal rmbAmount = 0;
            //foreach (DataRow dr in _dtIncome.Rows)
            //{
            //    rmbAmount += decimal.Parse(dr["RMBAmount"].ToString());
            //}

            //IncomeEntity income = new IncomeEntity()
            //{
            //    IncomeID = int.Parse(e.Row["IncomeID"].ToString()),//保留原内容               
            //    IncomeItemID = int.Parse(strIncomeItemId),//保留原内容               
            //    Voucher = e.Row["Voucher"].ToString(),
            //    Currency = e.Row["Currency"].ToString(),
            //    ExchangeRate = float.Parse(e.Row["ExchangeRate"].ToString()),
            //    RMBAmount = decimal.Parse(e.Row["RMBAmount"].ToString()),
            //    PaymentMethod = e.Row["PaymentMethod"].ToString(),
            //    PaymentAmount = decimal.Parse(e.Row["PaymentAmount"].ToString()),
            //    Time = DateTime.Parse(e.Row["Time"].ToString()).ToString("yyyy-MM-dd"),
            //    Transactor = e.Row["Transactor"].ToString(),
            //    Remark = e.Row["Remark"].ToString(),
            //};
            //IncomeItemCtrl.UpdateIncomeData(income);

            ////更新计划收入项“ReceivedPrice已收额(RMB)”,引发计划收入项列数据更新
            //DataRowView drv = BindingContext[_dtIncomeItem].Current as DataRowView;
            //drv["ReceivedPrice"] = rmbAmount;
        }

        void IncomeItem_ColumnChanged(object sender, DataColumnChangeEventArgs e)
        {
            //财务不可修改应收款项，如果确定不用，可删除
            IncomeItemEntity incomeItem = new IncomeItemEntity()
            {
                IncomeItemID = int.Parse(e.Row["IncomeItemID"].ToString()),//保留原内容               
                TourgroupID = e.Row["TourgroupID"].ToString(),//保留原内容
                //CustomerID = int.Parse(e.Row["CustomerID"].ToString()),
                CustomerName = e.Row["CustomerName"].ToString(),
                IncomeItem = e.Row["IncomeItem"].ToString(),
                PlanPrice = decimal.Parse(e.Row["PlanPrice"].ToString()),
                ReceivedPrice = e.Row["ReceivedPrice"].ToString() == "" ? 0 : decimal.Parse(e.Row["ReceivedPrice"].ToString()),
                AdjustPrice = decimal.Parse(e.Row["AdjustPrice"].ToString()),
                Remark = e.Row["Remark"].ToString()
            };
            IncomeItemCtrl.UpdateIncomeItemData(incomeItem);
        }
        /// <summary>
        /// 刷新计划收入网格数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            if (tourGroupInfoControl._TourGroupID == "") return;

            //终结状态后不能增加款项和增加收款
            TeamStateEnum state = TeamGroupCtrl.GetTourGroupState(tourGroupInfoControl._TourGroupID);
            if (state == TeamStateEnum.终结 || state == TeamStateEnum.取消 || state == TeamStateEnum.删除)
            {
                btnAddIncomeItem.Enabled = false;
                btnAddIncome.Enabled = false;
            }
            else
            {
                btnAddIncomeItem.Enabled = true;
                btnAddIncome.Enabled = true;
            }

            _dtIncomeItem = IncomeItemCtrl.GetIncomeItemData(tourGroupInfoControl._TourGroupID);
            incomeItemGridControl.DataSource = _dtIncomeItem;
            
            //财务不可修改应收款项
            //_dtIncomeItem.ColumnChanged += new DataColumnChangeEventHandler(IncomeItem_ColumnChanged);

            //初始化收款列表
            if (_dtIncomeItem.Rows.Count == 0)
            {
                LoadIncomeData("", "");
            }
            else
            {
                string incomeItemId = incomeItemGridView.GetRowCellValue(0, "IncomeItemID").ToString();
                LoadIncomeData(incomeItemId, "");
            }


            ////初始化显示‘团费’信息
            //DataTable dt = TeamGroupCtrl.GetTeamGroupRowData(tourGroupInfoControl._TourGroupID);
            //tbPlanPrice.EditValue = dt.Rows[0]["SaleTotalPrice"];
            //tbReceivePrice.EditValue = dt.Rows[0]["SaleTotalCost"];
        }
        /// <summary>
        /// 刷新收款录入网格数据
        /// </summary>
        /// <param name="incomeItemId"></param>
        private void LoadIncomeData(string incomeItemId,string incomeId)
        {
            if (incomeItemId == "")
            {
                incomeGridControl.DataSource = null;
            }
            else
            {
                _dtIncome = IncomeItemCtrl.GetIncomeData(incomeItemId);
                incomeGridControl.DataSource = _dtIncome;
                _dtIncome.ColumnChanged += new DataColumnChangeEventHandler(Income_ColumnChanged);
            }
            //选中指定项
            if (incomeId == "") return;
            for (int i = 0; i < incomeGridView.RowCount; i++)
            {
                if (incomeGridView.GetRowCellValue(i, "IncomeID").ToString() == incomeId)
                {
                    incomeGridView.FocusedRowHandle = i;
                    break;
                }
            }
        }


        #region 计划收入按钮事件

        private void btnAddIncomeItem_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(tourGroupInfoControl._TourGroupID))
                MessageBox.Show("还没有选择计划号", "错误", MessageBoxButtons.OK, MessageBoxIcon.Information);
            else
            {
                ChangeIncomeItemForm incomeItemForm = new ChangeIncomeItemForm(null,0);
                if (incomeItemForm.ShowDialog(this) == DialogResult.OK)
                {
                    incomeItemForm._IncomeItemEntity.TourgroupID = tourGroupInfoControl._TourGroupID;
                    incomeItemForm._IncomeItemEntity.TourgroupName = tourGroupInfoControl._TourGroupName;
                    incomeItemForm._IncomeItemEntity.CustomerName = tourGroupInfoControl._CustomerName;
                    IncomeItemCtrl.CreateIncomeItemData(incomeItemForm._IncomeItemEntity);

                    //如团已审核，则此次影响了‘费用表’数据，必须重新计算审核价格、审核成本,三处（团审核、收款录入、新增付款）完成此动作
                    //if (TeamGroupCtrl.GetTourGroupState(tourGroupInfoControl._TourGroupID) == TeamStateEnum.审核)
                    //    TeamGroupCtrl.UpdateTourGroupBudge(tourGroupInfoControl._TourGroupID);
                    
                    // 更新审核价格
                    TeamGroupCtrl.UpdateTourGroupBudgePrice(tourGroupInfoControl._TourGroupID);

                    btnRefresh.PerformClick();
                }
            }
        }
        /// <summary>
        /// 调差
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //private void btnAdjust_Click(object sender, EventArgs e)
        //{
        //    if (incomeItemGridView.FocusedRowHandle < 0) return;

        //    decimal ReceivedPrice = decimal.Parse(incomeItemGridView.GetRowCellValue(incomeItemGridView.FocusedRowHandle, "ReceivedPrice").ToString());
        //    decimal PlanPrice = decimal.Parse(incomeItemGridView.GetRowCellValue(incomeItemGridView.FocusedRowHandle, "PlanPrice").ToString());

        //    //更新计划收入项“AdjustPrice调整金额”,引发计划收入项列数据更新
        //    DataRowView drv = BindingContext[_dtIncomeItem].Current as DataRowView;
        //    drv["AdjustPrice"] = ReceivedPrice - PlanPrice;
        //}

        #endregion

        #region 收款录入按钮事件

        private void btnAddIncome_Click(object sender, EventArgs e)
        {
            if (incomeItemGridView.FocusedRowHandle < 0) return;

            string incomeItemId = incomeItemGridView.GetRowCellValue(incomeItemGridView.FocusedRowHandle, "IncomeItemID").ToString();

            if (string.IsNullOrEmpty(incomeItemId))
                MessageBox.Show("无法获得选中的计划收入项标识", "错误", MessageBoxButtons.OK, MessageBoxIcon.Information);
            else
            {
                AddIncomeForm incomeForm = new AddIncomeForm();
                incomeForm.tbRemark.Text = tourGroupInfoControl._CustomerName + " 支付 " + tourGroupInfoControl._TourGroupName + " " + incomeItemGridView.GetRowCellValue(incomeItemGridView.FocusedRowHandle, "IncomeItem").ToString();
                if (incomeForm.ShowDialog(this) == DialogResult.OK)
                {
                    incomeForm._IncomeEntity.IncomeItemID = int.Parse(incomeItemId);

                    string incomeId = IncomeItemCtrl.CreateIncomeData(incomeForm._IncomeEntity);
                    
                    //刷新界面
                    LoadIncomeData(incomeItemId, incomeId);

                    //以下是更新计划收入项代码
                    decimal rmbAmount = 0;
                    foreach (DataRow dr in _dtIncome.Rows)
                    {
                        rmbAmount += decimal.Parse(dr["RMBAmount"].ToString());
                    }
                    //更新计划收入项“ReceivedPrice已收额(RMB)”,引发计划收入项列数据更新
                    DataRowView drv = BindingContext[_dtIncomeItem].Current as DataRowView;
                    drv["ReceivedPrice"] = rmbAmount;

                    //更新数据库已收额
                    IncomeItemCtrl.UpdateIncomeItemReceivedPrice(incomeItemId, rmbAmount);

                    //更新团实际价格
                    TeamGroupCtrl.UpdateTourGroupRealPrice(tourGroupInfoControl._TourGroupID);

                    #region 计入流水账
                    if (incomeForm._IncomeEntity.PaymentMethod != "冲抵")
                    {
                        AccountManagerEntity entity = new AccountManagerEntity();
                        entity.Date = incomeForm._IncomeEntity.Time;
                        entity.Summary = incomeForm._IncomeEntity.Remark;
                        entity.Income = incomeForm._IncomeEntity.RMBAmount;
                        entity.Expenditure = 0;
                        entity.Remark = "";
                        entity.ItemType = 2;
                        entity.ItemID = incomeId;
                        entity.Voucher = incomeForm._IncomeEntity.Voucher;
                        entity.PaymentMethod = incomeForm._IncomeEntity.PaymentMethod;
                        switch (incomeForm._IncomeEntity.PaymentMethod)
                        {
                            case "现金":
                                entity.AccountType = AccountTypeEnum.现金.ToString();
                                break;
                            case "贝宝":
                                entity.AccountType = AccountTypeEnum.贝宝.ToString();
                                break;
                            case "其他":
                                entity.AccountType = AccountTypeEnum.其他.ToString();
                                break;
                            default:
                                entity.AccountType = AccountTypeEnum.银行.ToString();
                                break;
                        }

                        entity.Transactor = incomeForm._IncomeEntity.Transactor;

                        AccountManagerCtrl.CreateAccountManagerData(entity);
                    }
                    #endregion

                }
            }
        }
        private void btnDeleteIncome_Click(object sender, EventArgs e)
        {
            //if (incomeGridView.FocusedRowHandle < 0) return;

            //string incomeId = incomeGridView.GetRowCellValue(incomeGridView.FocusedRowHandle, "IncomeID").ToString();
            //IncomeItemCtrl.DeleteIncomeData(incomeId);

            //string incomeItemId = incomeItemGridView.GetRowCellValue(incomeItemGridView.FocusedRowHandle, "IncomeItemID").ToString();

            //LoadIncomeData(incomeItemId);
        }
        private void btnPrint_Click(object sender, EventArgs e)
        {
            if (incomeGridView.FocusedRowHandle < 0) return;
            IncomeDataSet ds = new IncomeDataSet();
            for (int i = 0; i < 2; i++)
            {
                ds.Tables["Income"].ImportRow(incomeGridView.GetDataRow(incomeGridView.FocusedRowHandle));
                ds.Tables["Income"].Rows[i]["TourgroupID"] = tourGroupInfoControl._TourGroupID;
                ds.Tables["Income"].Rows[i]["TourgroupName"] = tourGroupInfoControl._TourGroupName;
                ds.Tables["Income"].Rows[i]["RMBAmountG"] = MoneyHelper.ChMoney(decimal.Parse(incomeGridView.GetFocusedRowCellValue("RMBAmount").ToString()));
            }
           
            IncomeReport rpt = new IncomeReport();
            rpt.DataSource = ds;
            rpt.PrintDialog();
        }

        #endregion

        private void incomeItemGridView_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (e.FocusedRowHandle < 0) return;

            string incomeItemId = incomeItemGridView.GetRowCellValue(e.FocusedRowHandle, "IncomeItemID").ToString();
            LoadIncomeData(incomeItemId,"");
        }

        private void btnModifyVoucher_Click(object sender, EventArgs e)
        {
            if (incomeGridView.FocusedRowHandle < 0) return;

            if (incomeGridView.GetRowCellValue(incomeGridView.FocusedRowHandle, "Voucher").ToString() != "" )
            {
                MessageBox.Show("已有凭证号不能修改");
                return;
            }

            VoucherModifyForm voucherForm = new VoucherModifyForm();
            if (voucherForm.ShowDialog(this) == DialogResult.OK)
            {
                string incomeId = incomeGridView.GetRowCellValue(incomeGridView.FocusedRowHandle, "IncomeID").ToString();
                IncomeItemCtrl.UpdateIncomeVoucher(voucherForm.tbVoucher.Text, incomeId);
                //更新记账凭证
                AccountManagerCtrl.UpdateVoucherData("2", incomeId, voucherForm.tbVoucher.Text);//0为‘收款录入表’类型
                //刷新界面
                incomeGridView.SetRowCellValue(incomeGridView.FocusedRowHandle, "Voucher", voucherForm.tbVoucher.Text);
            }

        }

        private void btnModifyRemark_Click(object sender, EventArgs e)
        {
            if (incomeGridView.FocusedRowHandle < 0) return;

            RemarkModifyForm remarkForm = new RemarkModifyForm();

            if (remarkForm.ShowDialog(this) == DialogResult.OK)
            {
                string incomeId = incomeGridView.GetRowCellValue(incomeGridView.FocusedRowHandle, "IncomeID").ToString();
                string remark = incomeGridView.GetRowCellValue(incomeGridView.FocusedRowHandle, "Remark").ToString() + " " + remarkForm.tbRemark.Text;
                IncomeItemCtrl.UpdateIncomeRemark(remark, incomeId);
                //刷新界面
                incomeGridView.SetRowCellValue(incomeGridView.FocusedRowHandle, "Remark", remark);
            }

        }
    }
}
